package com.sgb.merchant.view.fragment;

import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.DemandListEntity;
import com.sgb.link.entity.merchant.DemandType;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.view.fragment.AppLazyFragment;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantFragmentListBinding;
import com.sgb.merchant.view.adapter.DemandListAdapter;
import com.sgb.merchant.viewmodel.InvestmentDemandViewmodel;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author: 王彬臣
 * @date: 2021/7/27
 * @Description: 招商引资首页 投资需求列表
 */
public class InvestmentDemandFragment extends AppLazyFragment {
    MerchantFragmentListBinding mBinding;
    InvestmentDemandViewmodel mViewModel;
    private boolean mIsLoadMore = false;
    private DemandListAdapter mAdapter;
    private List<DemandListEntity> mListInvestment=new ArrayList<>();
    private HashMap<String, Object>  mMap = new HashMap<>();;
    String no;



    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.merchant_fragment_list, container, false);
        mViewModel=new ViewModelProvider(this).get(InvestmentDemandViewmodel.class);
        init();
        return mBinding.getRoot();
    }



    public void init() {
        mBinding.recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        DividerDecoration.builder(getActivity())
                .color(getResources().getColor(R.color.color_f5f5f5))
                .size(1, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.recycler);
        mAdapter = new DemandListAdapter(mListInvestment);
        mAdapter.bindToRecyclerView(mBinding.recycler);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                no=mListInvestment.get(position).getNo();
                DialogHelper.showProgressDialog(getActivity(), "").setCanceledOnTouchOutside(true);
                mViewModel.getState(no);

            }
        });
        mBinding.refreshLayout.setEnableRefresh(false);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mViewModel.getInvestmentData(mIsLoadMore, mMap);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
               mIsLoadMore=false;
               refreshView();
            }
        });

        mViewModel.liveDataInvestment.observe(getActivity(),this::syncData);
        mViewModel.ldState.observe(getActivity(),state->{
            switch (state){//0未上架 1已删除 2正常
                case 0:
                    MToast.showToast(getActivity(),"当前数据已下架");
                    refreshView();
                    break;
                case 1:
                    MToast.showToast(getActivity(),"当前数据已删除");
                    refreshView();
                    break;
                case 2:
                    ActivityJump.startActivity(PathMerchant.DemandDetailActivity, Pair.create(RouterKey.NO,no));
                    break;
            }
        });

        mViewModel.ldType.observe(getActivity(),this::showTabLayout);
    }

    private void showTabLayout(List<DemandType> list) {
        if(list==null){
            return;
        }
        DemandType entity = new DemandType();
        entity.setDemandTypeName("全部");
        entity.setNo(null);
        list.add(0, entity);

        for (int a = 0; a < list.size(); a++) {
            mBinding.tabIndustryCategory.addTab(mBinding.tabIndustryCategory.newTab().setText(list.get(a).getDemandTypeName()).setTag(list.get(a).getNo()));
        }
        mBinding.tabIndustryCategory.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mMap.put("demandTypeNo", tab.getTag());
                mIsLoadMore=false;
                refreshView();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onClick(View v) {

    }
    public void refreshView() {

        mMap.put("orderByColumn", "desc");
        mIsLoadMore = false;
        DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        mViewModel.getInvestmentData(mIsLoadMore, mMap);
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    /**
     * 投资需求数据
     *
     * @param
     */
    public void syncData(ListResponse<List<DemandListEntity>> entity) {
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (mViewModel.pageNum == 1) {
            mListInvestment.clear();
        }
        if (entity.getList() != null) {
            mListInvestment.addAll(entity.getList());
        }
        if(mListInvestment.size()==0){
            mBinding.recycler.setVisibility(View.GONE);
            mBinding.errorView.setVisibility(View.VISIBLE);
        }else {
            mBinding.recycler.setVisibility(View.VISIBLE);
            mBinding.errorView.setVisibility(View.GONE);
        }
        mAdapter.notifyDataSetChanged();


        //
        if (entity.getCurrentPage()<entity.getTotalPage()) {
            mIsLoadMore=true;
            mBinding.refreshLayout.resetNoMoreData();
        } else {
            mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    protected void onLazyLoad() {
        mViewModel.getType();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_REFRESH) {
            refreshView();
        }
    }

}
